#!/usr/bin/python
# -*- coding: utf-8 -*-

from ConfigParser import *
from assis_const  import *


class Config :
	
	def __init__(self):

		self.g_name          = ""
		self.g_pass          = ""
		self.g_spreadsheet   = ""
		
		try:
			self.rcp             = RawConfigParser()
			self.cfgfile         = open(LOCAL_CONF, "r+")
			self.rcp.read(LOCAL_CONF)
			self.sections        = self.rcp.sections()
			self.g_name          = self.map_sections(CLOUD_SECTION)["name"]
			self.g_pass          = self.map_sections(CLOUD_SECTION)["pass"]
			self.g_spreadsheet   = self.map_sections(CLOUD_SECTION)["spreadsheet"]
		except IOError, ioe:
			print ("The file could not be opened !", LOCAL_CONF)
			self.cfgfile         = open(LOCAL_CONF, "w+")
		except NoSectionError, nse:
			print (CLOUD_SECTION, " section could not be found in ", LOCAL_CONF)
		except KeyError, ke:
			print (CLOUD_SECTION, " section does not contain following key: ", ke)
			self.g_spreadsheet   = "" 

	def iscomplete(self):
		
		return len(self.g_name) > 0 and len(self.g_pass) > 0 and len(self.g_spreadsheet) > 0

	def map_sections(self, section):
	
	    pairs = {}
	    options = self.rcp.options(section)
	    for option in options:
	        try:
	            pairs[option] = self.rcp.get(section, option)
	            if pairs[option] == -1:
	                DebugPrint("skip: %s" % option)
	        except:
	            print("exception on %s!" % option)
	            pairs[option] = None
	    
	    return pairs
	
	def save_in_obj(self, name, password, spreadsheet):
		
		self.g_name          = name
		self.g_pass          = password
		self.g_spreadsheet   = spreadsheet

		
	def save_settings(self, name, password, spreadsheet):

		try:
			self.sections.index(CLOUD_SECTION)
			self.rcp.remove_option(CLOUD_SECTION, "name")
			self.rcp.remove_option(CLOUD_SECTION, "pass")
			self.rcp.remove_option(CLOUD_SECTION, "spreadsheet")
		except ValueError, e:
			print (CLOUD_SECTION, " section could not be found in ", LOCAL_CONF)
			self.rcp.add_section(CLOUD_SECTION)
		
		self.rcp.set(CLOUD_SECTION, "name", name)
		self.rcp.set(CLOUD_SECTION, "pass", password)
		if spreadsheet is not None:
			self.rcp.set(CLOUD_SECTION, "spreadsheet", spreadsheet)	 
		self.rcp.write(self.cfgfile)
		self.cfgfile.close()
